//
//  ZYCRecourceWidomFileDetailViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/9/23.
//

#import "ZYCRecourceWidomFileDetailViewController.h"
#import "ZYCRecourceWidomFileDetailView.h"
#import "ZYCPublicFolderModel.h"
#import "ZYCVideoPlayerViewController.h"
#import "SESSFileLookController.h"
#import "ZYCLoginOutView.h"
#import "HWProgressView.h"
#import "ZYCDownloadManagerViewController.h"
#import "ZYCOnlinePreviewViewController.h"
#import "ZYCTipView.h"
#define kCachePath NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject

@interface ZYCRecourceWidomFileDetailViewController ()<UINavigationControllerDelegate,ZYCRecourceWidomFileDetailViewDelegate,ZYCLoginOutViewDelegate,UIDocumentInteractionControllerDelegate>

@property (nonatomic, strong)ZYCRecourceWidomFileDetailView *detailView;
@property (nonatomic, strong) ZYCLoginOutView *loginOutView;
@property (nonatomic, strong) ZYCTipView *tipView;

@end

@implementation ZYCRecourceWidomFileDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.delegate = self;
    [self.view addSubview:self.detailView];
    self.detailView.model = self.model;
}

- (NSString *)createSourceCenterFilePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *sourceCenterFolderPath = [cachePath stringByAppendingPathComponent:@"sourceFolder"];
    // 创建文件夹(资源中心)
    [fileManager createDirectoryAtPath:sourceCenterFolderPath withIntermediateDirectories:YES attributes:nil error:nil];
    return sourceCenterFolderPath;
}

#pragma mark - 下载
- (void)downloadWithModel:(ZYCPublicFolderModel *)model{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],model.filePath];
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSURLSessionDownloadTask *task = [[URLManager sharedURLManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        NSLog(@"downloadProgress%f",1.0*downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        [MrjSVProgressHUD showWithStatus:@"下载中..."];
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *filePath = [[self createSourceCenterFilePath] stringByAppendingPathComponent:model.name];
        return [NSURL fileURLWithPath:filePath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {
            [MrjSVProgressHUD showSuccessWithStatus:@"下载成功"];
            [self openAnnex:filePath];
        }else{
            [MrjSVProgressHUD showErrorWithStatus:@"下载失败"];
            NSLog(@"下载成功%@",error);
        }
    }];
    [task resume];
    

}

- (void)openAnnex:(NSURL *)filePath{
    if ([[filePath pathExtension] isEqualToString:@"xls"] || [[filePath pathExtension] isEqualToString:@"pptx"]) {
        UIDocumentInteractionController *documentController = [UIDocumentInteractionController
                                   interactionControllerWithURL:filePath];
        [documentController setDelegate:self];
        [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    }else if([[filePath pathExtension] isEqualToString:@"exe"] || [[filePath pathExtension] isEqualToString:@"rar"] || [[filePath pathExtension] isEqualToString:@"zip"]){
        ZYCDownloadManagerViewController *vc = [[ZYCDownloadManagerViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        SESSFileLookController *vc = [[SESSFileLookController alloc] initWithFilePath:filePath];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:vc animated:YES completion:nil];
    }
}

#pragma mark - ZYCLoginOutViewDelegate
- (void)loginOutViewDidClickLogout{
    NSString *path = [kCachePath stringByAppendingPathComponent:self.model.name];
    SESSFileLookController *vc = [[SESSFileLookController alloc] initWithFilePath:[NSURL URLWithString:path]];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}
#pragma mark - ZYCRecourceWidomFileDetailViewDelegate
// 关闭
- (void)recourceWidomFileDetailViewDidClose{
    [self.navigationController popViewControllerAnimated:YES];
}

//分享
- (void)recourceWidomFileDetailViewDidShare:(ZYCPublicFolderModel *)model{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],model.filePath]];
    NSArray *activityItems = @[url];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];
}

// 立即打开
- (void)recourceWidomFileDetailViewDidClickOpen:(ZYCPublicFolderModel *)model{
    NSURL *filePath = [NSURL URLWithString:[NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],model.filePath]];
    if([[filePath pathExtension] isEqualToString:@"exe"] || [[filePath pathExtension] isEqualToString:@"rar"] || [[filePath pathExtension] isEqualToString:@"zip"] || [[filePath pathExtension] isEqualToString:@"xls"]){
        [MrjToast makeToast:@"不支持这些类型的在线预览" makeView:self.view];
        
        
    }else{
        ZYCOnlinePreviewViewController *vc = [[ZYCOnlinePreviewViewController alloc] initWithFilePath:filePath];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:vc animated:YES completion:nil];
    }
}

// 立即下载
- (void)recourceWidomFileDetailViewDidClickDownload:(ZYCPublicFolderModel *)model{
    if ([[model.filePath pathExtension] isEqualToString:@"mp4"]) {// Mp4 或者音频
        [self playVideoWithModel:model];
    }else{
        [self clickDownloadAction:model];
    }
}


- (void)clickDownloadAction:(ZYCPublicFolderModel *)model{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [[self createSourceCenterFilePath] stringByAppendingPathComponent:model.name];
    if ([fileManager fileExistsAtPath:filePath]) {
        self.tipView.filePath = filePath;
        [self.tipView show];
    }else{
        [self downloadWithModel:model];
    }
}




- (void)playVideoWithModel:(ZYCPublicFolderModel *)model{
    ZYCVideoPlayerViewController *vc = [[ZYCVideoPlayerViewController alloc] init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

    



#pragma mark - UINavigationControllerDelegate
-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:[viewController isKindOfClass:[self class]] animated:YES];
}


#pragma mark - getters

- (ZYCTipView *)tipView {
    if (!_tipView) {
        ZYCWeakSelf
        _tipView = [[ZYCTipView alloc] initWithFrame:CGRectMake(0, 0, 280.0f, 155.0f)];
        _tipView.title = @"温馨提示";
        _tipView.content = @"是否打开文件?";
        _tipView.clickComfirmBlock = ^(NSString * _Nonnull filePath) {
            [weakSelf openAnnex:[NSURL fileURLWithPath:filePath]];
        };
        [self.navigationController.view addSubview:_tipView];
    }
    return _tipView;
}


- (ZYCRecourceWidomFileDetailView *)detailView {
    if (!_detailView) {
        _detailView = [[ZYCRecourceWidomFileDetailView alloc] initWithFrame:self.view.bounds];
        _detailView.delegate = self;
    }
    return _detailView;
}

- (ZYCLoginOutView *)loginOutView {
    if (!_loginOutView) {
        _loginOutView = [[ZYCLoginOutView alloc] initWithFrame:CGRectMake(0, 0, 280.0f, 155.0f)];
        _loginOutView.delegate = self;
        _loginOutView.title = @"温馨提示";
        _loginOutView.content = @"您已下载过该文件,是否直接打开?";
        [self.navigationController.view addSubview:_loginOutView];
    }
    return _loginOutView;
}


- (void)dealloc{
    self.navigationController.delegate = nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
